/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package frm.billingAndPaymentProcessing.managedbean;

import frm.billingAndPaymentProcessing.entity.InvoiceEntity;
import frm.billingAndPaymentProcessing.session.InvoiceSessionBean;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import crm.salesOrderProcessing.entity.LineItemEntity;
import crm.salesOrderProcessing.entity.DeliveryOrderEntity;
import frm.creditControl.entity.CreditAccountEntity;
import frm.creditControl.session.CreditControlSessionBean;
import java.text.ParseException;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.servlet.http.HttpServletRequest;
import crm.salesOrderProcessing.session.DeliveryOrderSessionBean;

/**
 *
 * @author xhx
 */
@ManagedBean
@ViewScoped
public class CreateInvoiceManagedBean {

    private Long receivedId;
    private DeliveryOrderEntity deliveryOrder;
    private InvoiceEntity invoice;
    private double amountPaid = 0;
    private CreditAccountEntity creditAccount;
    
    @EJB
    DeliveryOrderSessionBean deliveryOrderSessionBean;
    @EJB
    InvoiceSessionBean invoiceSessionBean;
    @EJB
    CreditControlSessionBean creditControlSessionBean;
    

    /** Creates a new instance of SendBillingRequestManagedBean */
    public CreateInvoiceManagedBean() {
        invoice = new InvoiceEntity();
        
    }
    public List<DeliveryOrderEntity> getDeliveryOrders(){
        return deliveryOrderSessionBean.getAllDeliveryOrders();
    }
    public List<DeliveryOrderEntity> getCIADeliveryOrders(){
        return deliveryOrderSessionBean.getAllCIADeliveryOrders();
    }
    public void createInvoice(Long selectDeliveryOrderId) throws IOException, ParseException {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        Long employeeId = (Long) request.getSession().getAttribute("userId");
        deliveryOrder = deliveryOrderSessionBean.getDeliveryOrderById(selectDeliveryOrderId);
        System.out.print("Test2...." + deliveryOrder.getId());
//        setDeliveryOrder(deliveryOrderSessionBean.getDeliveryOrderById(getReceivedId()));
        if (deliveryOrder.getInvoice() == null || deliveryOrder.getInvoice().isAbolished()) {
//            System.out.println("*************Test0"+deliveryOrder.getId());
//            System.out.println("*************Test"+deliveryOrder.getInvoice().getId());
            if (deliveryOrder.isIsCIAPayment()) {
                invoice.setInvoiceType("CIA payment Invoice");

            } else {
                invoice.setInvoiceType("Credit Sale Invoice");
                creditAccount = deliveryOrder.getParentSalesOrder().getCustomer().getCreditAccount();
                creditAccount.setCurrentBalance(calculateTotalAmount(deliveryOrder));
                creditControlSessionBean.saveChanges(creditAccount);
            }

            invoice.setIssuing_date(Calendar.getInstance().getTime());
            invoice.setCreatedBy(employeeId);
            invoice.setDueDate(getDue());
            invoice.setAmountPayable(calculateTotalAmount(deliveryOrder));

            invoice.setPayment_balance();

            
            invoice.setDeliveryOrder(deliveryOrder);
            invoiceSessionBean.createInvoice(invoice);
//      invoice.setDeliveryOrder(deliveryOrder);
//      invoiceSessionBean.saveChanges(invoice);
            deliveryOrder.setInvoice(invoice);
            deliveryOrderSessionBean.saveChanges(deliveryOrder);


//      System.out.println(deliveryOrder.getId());
//      System.out.println(invoice.getId());
            //send the inovice via emailing system
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Invoice Is Successfully Created", ""));
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("message", "From InvoiceCreation");
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("invoice", invoice);


            FacesContext.getCurrentInstance().getExternalContext().redirect("invoiceCreationResult.xhtml");

        }
        System.out.print("Test1....");
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "The Delivery Order Has Already be issued with an Invoice", ""));
        //setErrorMessage
        //direct to result/error page
    }

    private double calculateTotalAmount(DeliveryOrderEntity selectedDeliveryOrder) {
        double totalAmount = 0;
        List<LineItemEntity> lineItemList = selectedDeliveryOrder.getLineItems();
        for (LineItemEntity item : lineItemList) {
            totalAmount += item.getCumAmount();
        }

        return totalAmount;

    }
        private Date getDue() throws ParseException {
       

    Calendar daysLater = Calendar.getInstance();
        daysLater.add(Calendar.DAY_OF_MONTH, 15);
        Date convertedDate = daysLater.getTime();
      return convertedDate;
 
    }
    
    public void creatFinalInvoice() {
        setDeliveryOrder(deliveryOrderSessionBean.getDeliveryOrderById(getReceivedId()));
        //get customer ID
        //check amount payable
        //if 0
        //create Bill
        //update customer's credit account

        //else
        //send Message(customer x has xxx outstanding bill unpaid)
    }

    public DeliveryOrderEntity getDeliveryOrder() {
        return deliveryOrder;
    }

    public void setDeliveryOrder(DeliveryOrderEntity deliveryOrder) {
        this.deliveryOrder = deliveryOrder;
    }

    public InvoiceEntity getInvoice() {
        return invoice;
    }

    public void setInvoice(InvoiceEntity invoice) {
        this.invoice = invoice;
    }

    public double getAmountPaid() {
        return amountPaid;
    }

    public void setAmountPaid(double amountPaid) {
        this.amountPaid = amountPaid;
    }

    public Long getReceivedId() {
        return receivedId;
    }

    public void setReceivedId(Long receivedId) {
        this.receivedId = receivedId;
    }

    public CreditAccountEntity getCreditAccount() {
        return creditAccount;
    }

    public void setCreditAccount(CreditAccountEntity creditAccount) {
        this.creditAccount = creditAccount;
    }
}

